﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace LxCore
{
    public class DelegateCommand : ICommand
    {
        public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
        {
            _synchronizationContext = SynchronizationContext.Current;

            if (executeMethod == null || canExecuteMethod == null)
                throw new ArgumentNullException(nameof(executeMethod));

            _executeMethod = executeMethod;
            _canExecuteMethod = canExecuteMethod;
        }
        public DelegateCommand(Action executeMethod) : this(executeMethod, () => true)
        {
        }
        public event EventHandler? CanExecuteChanged;
        private SynchronizationContext _synchronizationContext;
        Action _executeMethod;
        Func<bool> _canExecuteMethod;

        public bool CanExecute(object? parameter)
        {
            return _canExecuteMethod();
        }

        public void Execute(object? parameter)
        {
            _executeMethod();
        }
        public void RaiseCanExecuteChanged()
        {
            var handler = CanExecuteChanged;
            if (handler != null)
            {
                if (_synchronizationContext != null && _synchronizationContext != SynchronizationContext.Current)
                    _synchronizationContext.Post((o) => handler.Invoke(this, EventArgs.Empty), null);
                else
                    handler.Invoke(this, EventArgs.Empty);
            }
        }
    }
}
